from PyQt5.QtWidgets import QPushButton, QDialog, QLineEdit, QMessageBox, QTreeView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5 import uic
from util.RedisUtil import *
import json
import uuid


class RedisConnect(QDialog):
    def __init__(self, parent):
        super(RedisConnect, self).__init__(parent)
        uic.loadUi('../ui/connect.ui', self)

        self.model = QStandardItemModel()
        self.parent().leftTree.setModel(self.model)
        self.parent().leftTree.setEditTriggers(QTreeView.NoEditTriggers)

        # 初始化连接
        with open('../config/config.conf', 'r') as file:
            for line in file:
                data_json = json.loads(line.strip())
                print(data_json)
                item = QStandardItem(data_json['name'])
                self.model.appendRow(item)

        # 输入框
        self.nameEdit: QLineEdit
        self.hostEdit: QLineEdit
        self.portEdit: QLineEdit
        self.authEdit: QLineEdit

        # 输入框设置默认值
        self.portEdit.setText('6379')

        # 按钮
        self.connectTest: QPushButton
        self.connectConfirm: QPushButton
        self.connectCancel: QPushButton

        # 按钮添加点击事件
        self.connectTest.clicked.connect(self.on_connect_test)
        self.connectConfirm.clicked.connect(self.on_connect_confirm)
        self.connectCancel.clicked.connect(self.on_connect_cancel)

    # 测试按钮点击事件
    def on_connect_test(self):
        text = self.get_text()
        r = get_connect(text[1], text[2], text[3])
        try:
            response = r.ping()
            print('response...', response)
            message_box = QMessageBox()
            if response:
                message_box.setWindowTitle("成功")
                message_box.setText("连接redis服务成功...")
            else:
                message_box.setWindowTitle("错误")
                message_box.setText("无法连接redis服务...")
        except redis.exceptions.ConnectionError:
            message_box.setWindowTitle("错误")
            message_box.setText("无法连接redis服务...")
        message_box.setStandardButtons(QMessageBox.Ok)
        message_box.exec_()

    # 确认按钮点击事件
    def on_connect_confirm(self):
        text = self.get_text()
        print("confirm..", text[0], text[1], text[2], text[3], )

        data_id = uuid.uuid4()
        item = QStandardItem(text[0])
        self.model.appendRow(item)
        config = {
            "id": str(data_id),
            "name": text[0],
            "host": text[1],
            "port": text[2],
            "auth": text[3],
            "level": 0
        }
        item.setData(config)
        with open('../config/config.conf', 'a') as file:
            json.dump(config, file)
            file.write('\n')
        self.close()
        self.clear()

    # 取消按钮点击事件
    def on_connect_cancel(self):
        self.close()

    def clear(self):
        self.nameEdit.setText('')
        self.hostEdit.setText('')
        self.authEdit.setText('')

    # 窗口关闭事件
    def closeEvent(self, event):
        self.parent().setEnabled(True)
        event.accept()

    # 获取输入框数据
    def get_text(self):
        name = self.nameEdit.text()
        host = self.hostEdit.text()
        port = self.portEdit.text()
        auth = self.authEdit.text()
        return name, host, port, auth


